package com.chat.client;

import com.chat.bean.News;

import javax.swing.text.ChangedCharSetException;
import java.io.*;
import java.net.Socket;
import java.util.Objects;
import java.util.Random;


public class ClientChat {
    private int id = 0;
    private String user = "";
    private String Sip = "127.0.0.1";
    private int Sport = 9700;
    private StringBuffer maspool = new StringBuffer();

    public ClientChat(String ip,int port) {
        this.Sip = ip;
        this.Sport = port;
    }

    //客户端请求数据
    public String putNews(String type,String data) throws IOException, ClassNotFoundException {

        Socket socket = new Socket(Sip, Sport);
        News news = new News(this.id,this.user,type,data.getBytes("utf-8"));
//        System.out.println(Sip+"\t"+Sport);
        //发送消息
        ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
        oos.writeObject(news);

        //得到返回数据
        ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
        News rnews = (News)ois.readObject();
        System.out.println(rnews.getData());
        String ts = new String(rnews.getData(),"utf-8");

        String[] split = ts.split("\t");
        StringBuilder sb = new StringBuilder();

        for (int i=0;i<split.length;i++){
            sb.append(split[i]).append("\n");
        }

        socket.close();
        oos.close();

        return sb.toString();

    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getUser() {
        return user;
    }

    public String getSip() {
        return Sip;
    }

    public int getSport() {
        return Sport;
    }

    public void setUser(String user) {
        this.user = user;
    }
}
